package com.dinadi.yidi.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.dinadi.yidi.R;


/**
 * author: JiaYu.He
 * Date: 2016-11-16
 * Time: 18:45
 */
public class UtilPopupWindow {
    private PopupWindowCallback callback;
    PopupWindow window;
    Activity activity;

    public interface PopupWindowCallback {
        void setContentViewlayout(View contentView);
    }

    /*setPopupWindow函数中的参数依次是：contex；
      要显示的popupwindow的窗体高度；popupwindow中要显示的布局；
      主activity的布局（这里是为了设置popupwindow在主activity的显示位置）；*/
    public void setPopupWindow(Context context, int windowHeight, View contentView, View parentView, int gravity) {

        if (callback != null) {
            callback.setContentViewlayout(contentView);
        }
        window = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, windowHeight, false);
        //   window.setBackgroundDrawable(new ColorDrawable(0x20000000));
        // 设置点击     窗口外边窗口消失
        window.setBackgroundDrawable(new BitmapDrawable());
        window.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击

        activity = (Activity) context;
        window.setFocusable(true);
        window.setAnimationStyle(R.style.dialogstyle);

        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//多加这一句，问题就解决了！这句的官方文档解释是：让窗口背景后面的任何东西变暗  
        final WindowManager.LayoutParams windowlp = activity.getWindow().getAttributes();
        windowlp.alpha = 0.5f;
        activity.getWindow().setAttributes(windowlp);
        window.showAtLocation(parentView, gravity, 0, 0);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                lp.alpha = 1f;
                activity.getWindow().setAttributes(lp);
            }
        });

    }

    public void dismiss() {
        window.dismiss();
    }

    public void timeDismiss() {
        new CountDownTimer(1000, 10) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                window.dismiss();
            }
        }.start();
    }

}
